#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
验证AES加密与服务器的兼容性
使用与Flutter完全相同的加密参数和算法
"""

import json
import base64
import time
import requests
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes

def test_server_aes_compatibility():
    """测试服务器AES兼容性"""
    print("🧪 =============== AES服务器兼容性测试 ===============")
    
    # 使用与Flutter完全相同的密钥
    SECRET_KEY = "qwertyuiop1234567654zaqwsxcderfv"
    secret_key = SECRET_KEY.encode('utf-8')[:32].ljust(32, b'\0')
    
    print(f"🔑 密钥: {SECRET_KEY}")
    print(f"🔑 密钥字节长度: {len(secret_key)}")
    
    # 准备测试数据（与Flutter相同的格式）
    test_data = {
        "commentId": 53,  # 使用存在的评论ID
        "timestamp": int(time.time())  # 使用int类型，与测试结果一致
    }
    
    print(f"📊 原始数据: {json.dumps(test_data)}")
    
    # 转为JSON字符串
    json_data = json.dumps(test_data, separators=(',', ':'))  # 紧凑格式，与Flutter一致
    print(f"📄 JSON字符串: {json_data}")
    print(f"📏 JSON长度: {len(json_data)} 字符")
    
    try:
        # AES加密（与Flutter完全相同的实现）
        print(f"\n🔐 开始AES加密...")
        
        # 生成随机IV
        iv = get_random_bytes(16)
        print(f"🔑 生成的IV: {base64.b64encode(iv).decode()}")
        
        # 创建AES加密器
        cipher = AES.new(secret_key, AES.MODE_CBC, iv)
        
        # 填充并加密
        padded_data = pad(json_data.encode('utf-8'), AES.block_size)
        encrypted = cipher.encrypt(padded_data)
        
        # 拼接IV和加密数据，然后Base64编码
        combined = iv + encrypted
        encrypted_b64 = base64.b64encode(combined).decode('utf-8')
        
        print(f"🔒 加密结果长度: {len(encrypted_b64)} 字符")
        print(f"🔒 加密数据: {encrypted_b64}")
        
        # 验证解密（确保我们的实现正确）
        print(f"\n🔓 验证解密...")
        combined_verify = base64.b64decode(encrypted_b64)
        iv_verify = combined_verify[:16]
        encrypted_verify = combined_verify[16:]
        
        cipher_verify = AES.new(secret_key, AES.MODE_CBC, iv_verify)
        decrypted = unpad(cipher_verify.decrypt(encrypted_verify), AES.block_size)
        decrypted_str = decrypted.decode('utf-8')
        
        print(f"📝 解密结果: {decrypted_str}")
        print(f"🔍 解密验证: {'✅ 成功' if decrypted_str == json_data else '❌ 失败'}")
        
        # 创建加密载荷
        payload = {
            "encrypted_data": encrypted_b64
        }
        
        print(f"\n📦 加密载荷: {json.dumps(payload)}")
        
        # 发送加密请求到服务器
        print(f"\n🚀 发送AES加密请求到服务器...")
        
        response = requests.post(
            "http://124.71.77.44:2233/comments/detail/",
            json=payload,
            headers={"Content-Type": "application/json"},
            timeout=10
        )
        
        print(f"📨 HTTP状态码: {response.status_code}")
        
        try:
            response_json = response.json()
            print(f"📨 AES响应: {json.dumps(response_json, ensure_ascii=False)}")
        except:
            print(f"📨 AES响应文本: {response.text}")
        
        # 对比：发送明文请求
        print(f"\n📝 发送明文请求对比...")
        
        plaintext_response = requests.post(
            "http://124.71.77.44:2233/comments/detail/",
            json=test_data,
            headers={"Content-Type": "application/json"},
            timeout=10
        )
        
        print(f"📨 明文HTTP状态码: {plaintext_response.status_code}")
        
        try:
            plaintext_json = plaintext_response.json()
            print(f"📨 明文响应: {json.dumps(plaintext_json, ensure_ascii=False)}")
        except:
            print(f"📨 明文响应文本: {plaintext_response.text}")
            
        # 生成curl测试命令
        print(f"\n📋 生成的curl命令:")
        print(f"# AES加密方式:")
        print(f'''curl -X POST "http://124.71.77.44:2233/comments/detail/" \\
  -H "Content-Type: application/json" \\
  -d '{json.dumps(payload)}' ''')
        
        print(f"\n# 明文方式:")
        print(f'''curl -X POST "http://124.71.77.44:2233/comments/detail/" \\
  -H "Content-Type: application/json" \\
  -d '{json.dumps(test_data)}' ''')
        
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()
    
    print(f"\n🏁 =============== 测试完成 ===============")

if __name__ == "__main__":
    test_server_aes_compatibility()
